package com.sskj.market.ui;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.bulong.rudeness.RudenessScreenHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.request.RequestOptions;
import com.scwang.smartrefresh.header.MaterialHeader;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.sskj.common.base.App;
import com.sskj.common.box.decoration.DividerLineItemDecoration;
import com.sskj.common.box.imageloader.GlideImageLoader;
import com.sskj.common.util.ClickUtil;
import com.sskj.common.util.RxSchedulersHelper;
import com.sskj.lib.Constans;
import com.sskj.lib.RConfig;
import com.sskj.lib.adapter.BaseAdapter;
import com.sskj.lib.adapter.ViewHolder;
import com.sskj.lib.base.BaseActivity;
import com.sskj.lib.bean.UserData;
import com.sskj.lib.model.room.UserViewModel;
import com.sskj.lib.util.AppCircleCheckUtil;
import com.sskj.lib.util.NumberUtil;
import com.sskj.market.R;
import com.sskj.market.R2;
import com.sskj.market.bean.HotShoppingDataBean;
import com.sskj.market.bean.ShoppingTitleBean;
import com.sskj.market.component.DaggerUserDataComponent;
import com.sskj.market.http.HttpConfig;
import com.sskj.market.presenter.ShoppingPresenter;
import com.sskj.market.util.GlideUtils;
import com.youth.banner.Banner;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;

/**
 * 商城Activity
 *
 * @author Hey
 * Create at  2019/07/25
 */
@Route(path = RConfig.MARKET_ACTIVITY_SHOPPING)
public class ShoppingActivity extends BaseActivity<ShoppingPresenter> {

    @BindView(R2.id.tvTitle)
    TextView tvTitle;
    @BindView(R2.id.tvRight)
    TextView tvRight;
    @BindView(R2.id.ivRight)
    ImageView ivRight;
    @BindView(R2.id.BannerSp)
    Banner BannerSp;
    @BindView(R2.id.tvHotShopping)
    TextView tvHotShopping;
    @BindView(R2.id.rvShopping)
    RecyclerView rvShopping;
    @BindView(R2.id.tvReturn)
    TextView tvReturn;
    @BindView(R2.id.rlShopping)
    RelativeLayout rlShopping;
    @BindView(R2.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R2.id.btShopping)
    Button btShopping;
    @BindView(R2.id.smartRefreshLayout)
    SmartRefreshLayout smartRefreshLayout;
    private BaseAdapter<HotShoppingDataBean.DataBean> adapter;
    private BaseAdapter<ShoppingTitleBean.CategoryBean> stAdapter;
    private ShoppingTitleBean stBean;
    private List<ShoppingTitleBean> stData = new ArrayList<>();
    private String is_pc = "1";
    private List<ShoppingTitleBean.SlidesBean> bannerList;
    private int page = 1;

    @Inject
    UserViewModel userViewModel;
    UserData userData;

    @Override
    public int getLayoutId() {
        return R.layout.market_activity_shopping;
    }

    @Override
    public ShoppingPresenter getPresenter() {
        return new ShoppingPresenter();
    }

    @SuppressLint("NewApi")
    @Override
    public void initView() {
        DaggerUserDataComponent.create().inject(this);
        userViewModel.getUsers().observe(this, users -> {
            if (users != null && users.size() > 0) {
                userData = users.get(0);
            } else {
                userData = null;
            }
        });
        tvReturn.setVisibility(View.VISIBLE);
        tvTitle.setText(App.INSTANCE.getString(R.string.market_shoppingActivity1));
        ivRight.setColorFilter(R.color.lib_618);
        //热门商品列表
        mPresenter.getHotShoppingData(page, true);
        //分类图片标题，轮播图
        mPresenter.getBannerData();
        BannerSp.setImageLoader(new GlideImageLoader());
        ivRight.setImageDrawable(getDrawable(R.mipmap.market_icon_sousuo));
        //搜索
        ClickUtil.click(300, ivRight, () -> {
            ARouter.getInstance().build(RConfig.MARKET_ACTIVITY_SEARCH).navigation();
        });
        //跳转到热门商品
        ClickUtil.click(300, rlShopping, () -> {
            ARouter.getInstance().build(RConfig.MARKET_ACTIVITY_HOT_COMMODITY).navigation();
        });

        //跳转到订单列表
        ClickUtil.click(300, btShopping, () -> {
            if (AppCircleCheckUtil.checkLogin(this, userData)) {
                ARouter.getInstance().build(RConfig.MARKET_MY_ORDER_LIST).navigation();
            }
        });

        //刷新
        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                page = 1;
                mPresenter.getHotShoppingData(page, false);
            }
        });
        smartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshLayout) {
                page++;
                mPresenter.getHotShoppingData(page, false);
            }
        });
    }

    @Override
    public void initData() {
        stBean = new ShoppingTitleBean();
        //recyclerview初始化

        recyclerView.setLayoutManager(new GridLayoutManager(this, 4));


        rvShopping.setLayoutManager(new GridLayoutManager(this, 2));


        adapter = new BaseAdapter<HotShoppingDataBean.DataBean>(R.layout.activity_shopping_item, null, rvShopping) {
            @SuppressLint("CheckResult")
            @Override
            public void bind(ViewHolder holder, HotShoppingDataBean.DataBean item) {

                holder.setText(R.id.tvTitleShopItem, item.getName())
                        .setText(R.id.tvMoneyShopItem, NumberUtil.keep2(item.getPrice()) + "LAC")
                        .setText(R.id.tvNumberShopItem, item.getPurchase_number() + App.INSTANCE.getString(R.string.market_shoppingActivity2));
                ImageView ivShopItem = holder.getView(R.id.ivShopItem);

                if (item.getPics().size() != 0) {
                    RequestOptions requestOptions = new RequestOptions();
                    requestOptions.placeholder(R.mipmap.market_loading_img);
                    Glide.with(ShoppingActivity.this).load(HttpConfig.BASE_IMG_URL + item.getPics().get(0)).apply(requestOptions).into(ivShopItem);
                }

                LinearLayout linearLayout = holder.getView(R.id.llItem);
                //跳转到详情
                ClickUtil.click(300, linearLayout, () -> {
                    ARouter.getInstance().build(RConfig.MARKET_ACTIVITY_COMMODITY_DETAILS).withInt("product_id", item.getId()).navigation();
                });
            }

        };
    }

    public void getHotShoppingDataSuccess(HotShoppingDataBean data) {
        if (data.getData() == null) {
            return;
        }

        if (page==1){
            adapter.setNewData(data.getData());
        }else {
            adapter.addData(data.getData());
        }
    }

    @SuppressLint("CheckResult")
    public void getBannerDataSuccess(ShoppingTitleBean data) {
        if (data == null) {
            return;
        }

        stAdapter = new BaseAdapter<ShoppingTitleBean.CategoryBean>(R.layout.shopping_title, null, recyclerView) {
            @Override
            public void bind(ViewHolder holder, ShoppingTitleBean.CategoryBean item) {
                ImageView ivTitleImg = holder.getView(R.id.ivTitleImg);
                holder.setText(R.id.tvTitleName, item.getTitle());

                RequestOptions requestOptions = new RequestOptions();
                requestOptions.placeholder(R.mipmap.market_loading_img);
                Glide.with(ShoppingActivity.this).load(HttpConfig.BASE_IMG_URL + item.getIcon()).into(ivTitleImg);

                LinearLayout llShoppingTitle = holder.getView(R.id.llShoppingTitle);
                ClickUtil.click(300, llShoppingTitle, () -> {
                    ARouter.getInstance().build(RConfig.MARKET_GOOD_CATEGORY).withString(Constans.TITLE, item.getTitle()).withInt(Constans.TYPE, item.getId()).navigation();
                });
            }
        };
        stAdapter.addData(data.getCategory());
        bannerList = data.getSlides();

        Observable.fromArray(data.getSlides())
                .map(bannerBeans -> {
                    List<String> imgUrls = new ArrayList<>();
                    for (int i = 0; i < bannerBeans.size(); i++) {
                        imgUrls.add(HttpConfig.BASE_IMG_URL + bannerBeans.get(i).getPic());
                    }
                    return imgUrls;
                }).compose(RxSchedulersHelper.io_main())
                .subscribe(strings -> {
                    if (this.BannerSp != null) {
                        this.BannerSp.setImages(strings);
                        this.BannerSp.start();
                    }
                });
    }

    public void getHotRefreshFinish() {
        if (smartRefreshLayout != null) {
            smartRefreshLayout.finishLoadMore();
            smartRefreshLayout.finishRefresh();
        }
    }
}
